#include "buffer.h"

buffer_t buffer_create(char* ptr, int size)
{
  buffer_t buf = {ptr, 0, 0, 0, size};
  return buf;
}

void buffer_put(buffer_t* buf, char c)
{
  int size = buf->size;
  if ((buf->end + 1) % size != buf->begin){
    buf->data[buf->end] = c;
    buf->end = (buf->end + 1) % size;
    buf->available += 1;
  }
  else {
    //buffer is full, keep going by circle
    buf->data[buf->end] = c;
    buf->begin  = (buf->begin + 1) % size;
    buf->end    = (buf->end + 1) % size;
  }
}

char buffer_get(buffer_t* buf)
{
  if (buf->end != buf->begin){
    char temp = buf->data[buf->begin];
    buf->begin = (buf->begin + 1) % buf->size;
    buf->available -= 1;
    return temp;
  }
  else {
    //buffer empty
    buf->available = 0;
    return 0; //TODO: Add error handling support
  }
}

void buffer_flush(buffer_t* buf)
{
  buf->begin = 0;
  buf->end = 0;
  buf->available = 0;
}
 